import {
  Body,
  Controller,
  HttpStatus,
  HttpCode,
  UsePipes,
  Post,
  Put,
  Delete,
  UseInterceptors,
} from '@nestjs/common';
import { classToPlain } from 'class-transformer';
import { IdDto } from 'src/common/dto/id.dto';
import { DtoPipe } from '../common/pipe/dto.pipe';
import { CustomerService } from './customer.service';
import { CustomerSearchDto } from './dto/customer.search.dto';
import { CustomerEntity } from './customer.entity';
import { CustomerInsertDto } from './dto/customer.insert.dto';
import { CustomerUpdateDto } from './dto/customer.update.dto';
import { ResultApiInterceptor } from 'src/common/interceptor/result.api.interceptor';

@Controller('/api/customer')
export class CustomerController {
  constructor(private readonly customerService: CustomerService) {}

  // 获取列表
  @Post('/list')
  @UsePipes(DtoPipe)
  @UseInterceptors(ResultApiInterceptor)
  @HttpCode(HttpStatus.OK)
  async get(@Body() body: CustomerSearchDto): Promise<any> {
    const list: CustomerEntity[] =
      await this.customerService.getManyAndCount(body);
    return classToPlain(list);
  }

  /**
   * 根据id查询用户
   * @param Param 用户id
   * @function classToPlain 表示使用class-transformer内置方法返回数据（eg：可能涉及到排除某个字段，在entity中使用@Exclude()进行排除）
   */
  @Post('/id')
  @HttpCode(HttpStatus.OK)
  async findOne(@Body() body: IdDto): Promise<any> {
    const findOneById: CustomerEntity = await this.customerService.findOneById(
      body.id,
    );
    return classToPlain(findOneById); // 使用nestjs自带的序列化返回值成功
  }

  // 新增
  @Post('/add')
  @UsePipes(DtoPipe)
  @UseInterceptors(ResultApiInterceptor)
  @HttpCode(HttpStatus.OK)
  async add(@Body() bodys: CustomerInsertDto): Promise<boolean> {
    return await this.customerService.save(bodys);
  }

  // 编辑
  @Put('/edit')
  @UsePipes(DtoPipe)
  @HttpCode(HttpStatus.OK)
  async edit(@Body() body: CustomerUpdateDto): Promise<any> {
    return await this.customerService.updateById(body);
  }

  // 删除
  @Delete('/delete')
  @UsePipes(DtoPipe)
  @HttpCode(HttpStatus.OK)
  async delete(@Body() request: IdDto): Promise<any> {
    return await this.customerService.deleteById(request);
  }
}
